﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Cryptography;
using System.Text;

namespace Bright.NetCore.Api.Filter
{
    /// <summary>
    /// 全局异常过滤
    /// </summary>
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var status = 500;
            var exception = context.Exception;
            var requestBody = context.HttpContext.Request.Body;
            if (requestBody != null)
            {
                context.HttpContext.Request.EnableBuffering();//启用倒带, 读取request.body里的的参数, 还必须在在Program.cs里也启用倒带功能
                context.HttpContext.Request.Body.Position = 0;
                using var reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8);
                string? requestBodyStr = reader.ReadToEndAsync().Result;
            }

            var responseData = new ObjectResult(new { Msg = exception.Message }) { StatusCode = status };
            if (exception is CryptographicException apiEx)
            {
                responseData = new ObjectResult(new { Msg = $"加密服务异常： {exception.Message}" }) { StatusCode = status };
            }
            context.Result = responseData;

            context.ExceptionHandled = true;
        }
    }
}
